<template>
  <div class="case-list-container">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" ref="searchFormRef">
        <el-row :gutter="20">
          <el-col :md="8" :sm="12">
            <el-form-item label="案件名称" prop="caseName">
              <el-input v-model="searchForm.caseName" placeholder="输入案件名称关键词" clearable />
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="12">
            <el-form-item label="案件类型" prop="caseType">
              <el-select v-model="searchForm.caseType" placeholder="全部类型" clearable>
                <el-option
                    v-for="item in caseTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="12">
            <el-form-item label="申请时间" prop="dateRange">
              <el-date-picker
                  v-model="searchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="12">
            <el-form-item label="案件状态" prop="status">
              <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
                <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="12">
            <el-form-item label="申请人" prop="applicant">
              <el-input v-model="searchForm.applicant" placeholder="输入申请人姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :md="8" :sm="12">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
              <el-button type="text" @click="toggleAdvanced = !toggleAdvanced">
                {{ toggleAdvanced ? '简化搜索' : '高级搜索' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <div v-if="toggleAdvanced" class="advanced-search">
          <el-row :gutter="20">
            <el-col :md="8" :sm="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="searchForm.phone" placeholder="输入联系电话" clearable />
              </el-form-item>
            </el-col>
            <el-col :md="8" :sm="12">
              <el-form-item label="处理人" prop="processor">
                <el-input v-model="searchForm.processor" placeholder="输入处理人" clearable />
              </el-form-item>
            </el-col>
            <el-col :md="8" :sm="12">
              <el-form-item label="优先级" prop="priority">
                <el-select v-model="searchForm.priority" placeholder="全部优先级" clearable>
                  <el-option label="紧急" value="high" />
                  <el-option label="普通" value="normal" />
                  <el-option label="低" value="low" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </el-card>

    <el-card class="operation-card">
      <el-button type="primary" icon="plus" @click="handleCreate">新建案件</el-button>
      <el-button :disabled="!hasSelected" icon="delete" @click="batchDelete">批量删除</el-button>
      <el-button :disabled="!hasSelected" type="success" icon="share" @click="batchSubmit">批量提交</el-button>
      <el-button type="info" icon="download" @click="exportData">导出数据</el-button>
      <el-button icon="refresh" @click="refreshList">刷新</el-button>
    </el-card>

    <el-card>
      <el-table
          v-loading="loading"
          :data="caseStore.cases"
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="caseName" label="案件名称" min-width="180">
          <template #default="{ row }">
            <router-link :to="`/case/detail/${row.id}`" class="case-link">
              {{ row.caseName }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="caseType" label="案件类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getCaseTypeTag(row.caseType)">
              {{ caseTypeMap[row.caseType] || row.caseType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applicant" label="申请人" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ statusMap[row.status] || row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180" sortable>
          <template #default="{ row }">
            {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm') }}
          </template>
        </el-table-column>
        <el-table-column prop="processor" label="处理人" width="120" />
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTag(row.priority)">
              {{ priorityMap[row.priority] || row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleDetail(row)">详情</el-button>
            <el-button
                size="small"
                type="primary"
                :disabled="row.status !== 'draft'"
                @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
                size="small"
                type="success"
                :disabled="row.status !== 'draft'"
                @click="handleSubmit(row.id)"
            >
              提交
            </el-button>
            <el-popconfirm
                title="确定要删除此案件吗？"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="handleDelete(row.id)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="caseStore.pagination.total"
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            @current-change="fetchData"
            @size-change="handleSizeChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { ElMessage,ElPagination } from 'element-plus'
import { useCaseStore } from '@/stores/caseStore'

const router = useRouter()
const caseStore = useCaseStore()

// 搜索表单
const searchForm = reactive({
  caseName: '',
  caseType: '',
  dateRange: [],
  status: '',
  applicant: '',
  phone: '',
  processor: '',
  priority: ''
})
const searchFormRef = ref(null)

const toggleAdvanced = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  size: 10
})

// 表格加载状态
const loading = ref(false)

// 多选
const selectedCases = ref([])
const hasSelected = computed(() => selectedCases.value.length > 0)

// 案件类型选项和映射
const caseTypeOptions = [
  { value: 'civil', label: '民事案件' },
  { value: 'criminal', label: '刑事案件' },
  { value: 'administrative', label: '行政案件' },
  { value: 'commercial', label: '商事案件' }
]

const caseTypeMap = {
  civil: '民事案件',
  criminal: '刑事案件',
  administrative: '行政案件',
  commercial: '商事案件'
}

// 案件状态映射
const statusMap = {
  draft: '草稿',
  reviewing: '审核中',
  approved: '已通过',
  rejected: '已驳回',
  processing: '处理中',
  completed: '已完成',
  closed: '已关闭'
}

// 优先级映射
const priorityMap = {
  high: '紧急',
  normal: '普通',
  low: '低'
}

// 状态选项
const statusOptions = [
  { value: 'draft', label: '草稿' },
  { value: 'reviewing', label: '审核中' },
  { value: 'approved', label: '已通过' },
  { value: 'rejected', label: '已驳回' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'closed', label: '已关闭' }
]

// 获取tag类型
const getCaseTypeTag = (type) => {
  const map = {
    civil: 'success',
    criminal: 'danger',
    administrative: 'primary',
    commercial: 'warning'
  }
  return map[type] || ''
}

const getStatusTag = (status) => {
  const map = {
    draft: 'info',
    reviewing: 'warning',
    approved: 'success',
    rejected: 'danger',
    processing: '',
    completed: 'success',
    closed: 'info'
  }
  return map[status] || ''
}

const getPriorityTag = (priority) => {
  const map = {
    high: 'danger',
    normal: 'info',
    low: ''
  }
  return map[priority] || ''
}

// 初始加载数据
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }

    // 如果有时间范围参数
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }

    const result =  await caseStore.fetchCases(params)

    console.log('result: ', result)

    caseStore.cases  = result.data
    pagination.size = result.pagination.size
    pagination.page = result.pagination.page
    pagination.total = result.pagination.total
  } catch (error) {
    ElMessage.error('加载失败: ' + (error.message || '服务器错误'))
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.caseName = ''
  searchForm.caseType = ''
  searchForm.dateRange = []
  searchForm.status = ''
  searchForm.applicant = ''
  searchForm.phone = ''
  searchForm.processor = ''
  searchForm.priority = ''
  handleSearch()
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchData()
}

// 多选处理
const handleSelectionChange = (selection) => {
  selectedCases.value = selection
}

// 新建案件
const handleCreate = () => {
  router.push('/case/apply')
}

// 刷新列表
const refreshList = () => {
  fetchData()
}

// 导出数据
const exportData = async () => {
  try {
    const params = {
      ...searchForm,
      format: 'xlsx'
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }

    if (selectedCases.value.length > 0) {
      params.ids = selectedCases.value.map(item => item.id)
    }

    await CaseApi.exportCases(params)
    ElMessage.success('导出成功，请查收下载文件')
  } catch (error) {
    ElMessage.error('导出失败: ' + (error.message || '服务器错误'))
  }
}

// 查看详情
const handleDetail = (row) => {
  router.push(`/case/detail/${row.id}`)
}

// 编辑案件
const handleEdit = (row) => {
  router.push(`/case/edit/${row.id}`)
}

// 提交案件
const handleSubmit = async (id) => {
  try {
    await caseStore.submitCase(id)
    ElMessage.success('案件提交成功')
    fetchData()
  } catch (error) {
    ElMessage.error('提交失败: ' + (error.message || '服务器错误'))
  }
}

// 删除案件
const handleDelete = async (id) => {
  try {
    await caseStore.deleteCase(id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    ElMessage.error('删除失败: ' + (error.message || '服务器错误'))
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    const ids = selectedCases.value.map(item => item.id)
    await Promise.all(ids.map(id => caseStore.deleteCase(id)))
    ElMessage.success(`成功删除${ids.length}个案件`)
    selectedCases.value = []
    fetchData()
  } catch (error) {
    ElMessage.error('批量删除失败: ' + (error.message || '服务器错误'))
  }
}

// 批量提交
const batchSubmit = async () => {
  try {
    const ids = selectedCases.value.map(item => item.id)
    await Promise.all(ids.map(id => caseStore.submitCase(id)))
    ElMessage.success(`成功提交${ids.length}个案件`)
    selectedCases.value = []
    fetchData()
  } catch (error) {
    ElMessage.error('批量提交失败: ' + (error.message || '服务器错误'))
  }
}
</script>

<style scoped>
.case-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.operation-card {
  margin-bottom: 20px;
}

.case-link {
  color: var(--el-color-primary);
  text-decoration: none;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.advanced-search {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}
</style>